package com.gykfbxxh.imovie.utils;

import android.os.Looper;

import com.app.utils.util.ToastUtils;
import com.gykfbxxh.imovie.AppApplication;
import com.gykfbxxh.imovie.manager.AppManager;

/**
 * Created by xuxinghai
 * On 2017/8/17
 * 全局异常类
 */

public class AppExceptionHandler implements Thread.UncaughtExceptionHandler {

    private Thread.UncaughtExceptionHandler mDefaultHandler;
    public static final String TAG = "CatchExcep";
    AppApplication application;

    public AppExceptionHandler(AppApplication application){
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.application = application;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
//        if(!handleException(ex) && mDefaultHandler != null){
        if(!handleException(ex) && mDefaultHandler != null){
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);

        }else{
//        	Writer writer = new StringWriter();
//        	PrintWriter pw = new PrintWriter(writer);
//        	ex.printStackTrace(pw);
//        	String errorresult = writer.toString();
//        	saveError(errorresult);
//            Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
//            PendingIntent restartIntent = PendingIntent.getActivity(
//                    application.getApplicationContext(), 0, intent,
//                    Intent.FLAG_ACTIVITY_NEW_TASK);
//            //退出程序
//            AlarmManager mgr = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
//            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
//                    restartIntent); //// 1秒钟后重启应用
            AppManager.getAppManager().finishAllActivity();
            //杀死该应用进程
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
    private void saveError(String s){
//    	File file=AppFileUtils.getErrorFile();
//    	FileOutputStream fileOutputStream=null;
//		try {
//			fileOutputStream = new FileOutputStream(file);
//			fileOutputStream.flush();
//			fileOutputStream.write(s.getBytes());
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally{
//			try {
//				fileOutputStream.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}

    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        //使用Toast来显示异常信息
        new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                ToastUtils.showText("很抱歉,程序出现无法检测的异常,即将退出.");
                Looper.loop();

            }
        }.start();
        return true;
    }
}